package com.xsp.util;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.InputStream;

/**
 * @author xsp
 * @date 2024/1/2
 * @desc
 */
public class MyBatisHelper {
    private static SqlSessionFactory sessionFactory;

    static {
        InputStream inputStream = null;
        try {
            inputStream = Resources.getResourceAsStream("mybatis-config.xml");
            sessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static SqlSession createSqlSession() {
        if (sessionFactory != null) {
            return sessionFactory.openSession();
        }
        return null;
    }

    public static SqlSession createSqlSession(boolean autoCommit) {
        if (sessionFactory != null) {
            return sessionFactory.openSession(autoCommit);
        }
        return null;
    }

    public static void close(SqlSession sqlSession) {
        if (sqlSession != null) {
            sqlSession.close();
        }
    }

}
